<template>
  <md-page title="精彩瞬间">
    <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
      <view class="list">
        <view class="item" v-for="item in data.list" :key="item.id" @click="() => handleDetail(item)">
          <image class="image" :src="item.img" />
          <view class="text">{{ item.title }}</view>
        </view>
      </view>
    </mescroll-body>
  </md-page>
</template>

<script setup lang="ts">
import { reactive } from 'vue';
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import useMescroll from '@/uni_modules/mescroll-uni/hooks/useMescroll.js';
const { mescrollInit, downCallback } = useMescroll(onPageScroll, onReachBottom);
// 接口
import { moments } from '@/api';
import type { Index } from '@/api/data';

const data = reactive<{ list: Index.Moments.Data[] }>({
  list: [],
});

// 跳链接
const handleDetail = (item: Index.Moments.Data) => {
  let url = '';
  // link_type 1 跳公众号 2 跳详情
  if (item.link_type === 1) {
    url = '/pages/other/webview/index?url=' + encodeURIComponent(item.link);
  } else {
    url = '/pages/other/moment-images/detail?id=' + item.id;
  }
  uni.navigateTo({ url });
};

// 上拉加载的回调: 其中num:当前页 从1开始, size:每页数据条数,默认10
const upCallback = (mescroll: any) => {
  moments({ page: mescroll.num, limit: mescroll.size })
    .then(res => {
      const curPageData = res?.data?.data || []; // 当前页数据
      if (mescroll.num == 1) data.list = []; // 第一页需手动制空列表
      data.list = data.list.concat(curPageData); //追加新数据
      //方法一(推荐): 后台接口有返回列表的总页数 totalPage
      mescroll.endByPage(curPageData.length, res?.data?.total || 0);
    })
    .catch(() => {
      mescroll.endErr(); // 请求失败, 结束加载
    });
};

const loaded = () => {
  console.log('加载完成');
};
</script>

<style lang="scss" scoped>
// .container {
// 	overflow-y: auto;
// }
.list {
  padding: 28rpx;
  .item {
    margin-bottom: 20rpx;
    position: relative;
    width: 100%;
    height: 300rpx;
    .image {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 300rpx;
      border-radius: 20rpx;
      overflow: hidden;
    }
    .text {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 60rpx;
      line-height: 60rpx;
      text-align: center;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      color: 40rpx;
    }
  }
}
</style>
